import numpy
import torch
import matplotlib.pyplot as plt

learning_rate = 0.01
# 1.导入数据
x = torch.rand([500,1])
y_true = x*3 + 0.8

w = torch.rand([1,1],requires_grad=True)

b = torch.tensor(0,requires_grad=True,dtype=torch.float32)










# 4 通过循环实现反向传播

for i in range(3000):
# 2.通过模型计算 y_predict
    y_predict = torch.matmul(x, w) + b
    
# 3.计算loss


    loss = (y_true - y_predict).pow(2).mean()
    if w.grad is not None:
        w.data.zero_()  # .data 是浅拷贝
    if b.grad is not None:
        b.data.zero_()

    loss.backward()
    w.data = w.data - learning_rate*w.grad
    b.data = b.data - learning_rate*b.grad
    print("w ,b , loss",w.item(),b.item(),loss.item())


plt.figure(figsize=(20,8))

plt.scatter(x.numpy().reshape(-1), y_true.numpy().reshape(-1))

y_predict = torch.matmul(x, w) + b
plt.plot(x.numpy().reshape(-1), y_predict.detach().numpy().reshape(-1),c="r")

plt.show()
